package com.example.t_mb_03

import android.media.MediaPlayer
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {

    var mediaPlayers : MediaPlayer? = null

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(
            flutterEngine.dartExecutor.binaryMessenger,
            "music_channel"
        ).setMethodCallHandler { call, result ->
            when(call.method){
                "lead" -> lead(call, result)
                "play" -> play(call, result)
                "stop" -> stop(call, result)
            }
        }
    }

    private fun lead(call: MethodCall, result: MethodChannel.Result){
        var path = call.argument<String>("path") ?: run {
            return
        }
        try {
            var player = MediaPlayer().apply {
                setDataSource(path);
                prepareAsync()
            }
            mediaPlayers = player
            player.setOnPreparedListener {
                result.success(null)
            }
        }
        catch (e : Exception){
            result.error("lead", "lead", null);
        }
    }

    private fun play(call: MethodCall, result: MethodChannel.Result){
        var player = mediaPlayers;
        if(player == null){
            result.error("play", "play", null);
            return
        }
        try {
            player.start()
            result.success(null)
        }

        catch (e : Exception){
            result.error("play", "play", null);
        }
    }

    private fun stop(call: MethodCall, result: MethodChannel.Result){
        var player = mediaPlayers;
        if(player == null){
            result.error("stop", "stop", null);
            return
        }
        try {
            player.stop()
            result.success(null)
        }

        catch (e : Exception){
            result.error("stop", "stop", null);
        }
    }
}
